﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace JH
{
    public static class GetUniqueRealization
    {
        /// <summary>
        /// 在集合里找到唯一的值，找到多个或未找到将引发异常
        /// </summary>
        public static T GetUniqueEm<T>(this IEnumerable<T> enumerable, Predicate<T> find = null)
        {
            var list = enumerable.ToList();
            var findList = (find == null ? list : list.FindAll(find)).ToArray();
            return findList.Length switch
            {
                > 1 => throw new Exception($"集合{enumerable.GetType()}中含有多个{typeof(T)}"),
                0 => throw new Exception($"集合{enumerable.GetType()}中不存在满足查找条件的元素!"),
                _ => findList[0]
            };
        }

        /// <summary>
        /// 在集合里找到唯一的值，找到多个将引发异常，未找到返回默认值
        /// </summary>
        public static T GetUniqueOrDefaultEm<T>(this IEnumerable<T> enumerable, Predicate<T> find = null)
        {
            var list = enumerable.ToList();
            var findList = (find == null ? list : list.FindAll(find)).ToArray();
            return findList.Length switch
            {
                > 1 => throw new Exception($"集合{enumerable.GetType()}中含有多个{typeof(T)}"),
                0 => default,
                _ => findList[0]
            };
        }
    }
}